package com.yundashi.updateapp

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.yundashi.updateapputils.constant.DownLoadBy
import com.yundashi.updateapputils.constant.UiType
import com.yundashi.updateapputils.extension.log
import com.yundashi.updateapputils.listener.OnBtnClickListener
import com.yundashi.updateapputils.listener.OnInitUiListener
import com.yundashi.updateapputils.listener.UpdateDownloadListener
import com.yundashi.updateapputils.model.UiConfig
import com.yundashi.updateapputils.model.UpdateConfig
import com.yundashi.updateapputils.update.UpdateAppUtils
import com.yundashi.updateapputils.util.AppUtil
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    //    private val apkUrl = "http://uyaoguishort-video.oss-cn-beijing.aliyuncs.com/app-debug.apk"
    private val apkUrl =
        "http://haoyao.oss-cn-beijing.aliyuncs.com/20210308/bfa5f0aca57a4c89955da460bea16ec8.apk"
    private val apkUrl2 =
        "http://haoyao.oss-cn-beijing.aliyuncs.com/20210412/bb023fcb300a47c1834e8476fd8886c2.bin"
    private val updateTitle = "发现新版本V2.0.0"
    private val updateContent = "1、Kotlin重构版\n2、支持自定义UI\n3、增加md5校验\n4、更多功能等你探索"
    private val apkSavePaths =
        Environment.getExternalStorageDirectory().absolutePath + "/teprinciple"


    /**
     *1.3.8测试
     * */
    private var newApkType = 1 //新版本类型 1 debug   2 release

    private val installType = 7 //0默认安装 1root安装 2俊鹏广播安装 3印象service安装） 6 灵信 7圣创
    private val debugUrl_2722 = "https://haoyao.oss-cn-beijing.aliyuncs.com/20221101/c001b27ea2ea45c28509d091c9289862.apk"
    private val releaseUrl_2722 = "https://haoyao.oss-cn-beijing.aliyuncs.com/20221101/3be279c8470b41f8bdbe99746809db3d.apk"
    private val newVersionCode_2722 = 2722
    private val newVersion_2722 = "2.7.22"

    private val debugUrl_2731 = "https://haoyao.oss-cn-beijing.aliyuncs.com/20221103/0e53806c2a7344ff96c93c254d0b7bca.apk"
    private val releaseUrl_2731 = "https://haoyao.oss-cn-beijing.aliyuncs.com/20221103/52bb6e01d3e34e00bea8ee06f7b4d6b3.apk"
    private val newVersionCode_2731 = 2731
    private val newVersion_2731 = "2.7.31"


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        UpdateAppUtils.init(this)

        // 基本使用
        btn_basic_use.setOnClickListener {
            AppUtil.instance.appDownload(
                apkUrl, updateContent, updateTitle, UpdateConfig(
                    isSilent = true,
                    alwaysShowDownLoadDialog = true,
                    installType = 1,
                    apkSavePath = apkSavePaths
                ), UiConfig(uiType = UiType.SIMPLE), object : UpdateDownloadListener {
                    override fun onStart() {

                    }

                    override fun onDownload(progress: Int) {

                    }

                    override fun onFinish(filePath: String) {
                        Log.d("MainActivity", filePath)
                    }

                    override fun onError(e: Throwable) {

                    }

                }
            )
        }

        // 浏览器下载
        btn_download_by_browser.setOnClickListener {

            // 使用SpannableString
            val content = SpanUtils(this)
                .appendLine("1、Kotlin重构版")
                .appendLine("2、支持自定义UI").setForegroundColor(Color.RED)
                .appendLine("3、增加md5校验").setForegroundColor(Color.parseColor("#88e16531"))
                .setFontSize(20, true)
                .appendLine("4、更多功能等你探索").setBoldItalic()
                .appendLine().appendImage(R.mipmap.ic_launcher).setBoldItalic()
                .create()

            UpdateAppUtils
                .getInstance()
                .apkUrl(apkUrl)
                .updateTitle(updateTitle)
                .updateContent(content)
                .updateConfig(UpdateConfig().apply {
                    downloadBy = DownLoadBy.BROWSER
//                     alwaysShow = false
                    serverVersionName = "2.0.0"
                })
                .uiConfig(UiConfig(uiType = UiType.PLENTIFUL))

                // 设置 取消 按钮点击事件
                .setCancelBtnClickListener(object : OnBtnClickListener {
                    override fun onClick(): Boolean {
                        Toast.makeText(this@MainActivity, "cancel btn click", Toast.LENGTH_SHORT)
                            .show()
                        return false // 事件是否消费，是否需要传递下去。false-会执行原有点击逻辑，true-只执行本次设置的点击逻辑
                    }
                })

                // 设置 立即更新 按钮点击事件
                .setUpdateBtnClickListener(object : OnBtnClickListener {
                    override fun onClick(): Boolean {
                        Toast.makeText(this@MainActivity, "update btn click", Toast.LENGTH_SHORT)
                            .show()
                        return false // 事件是否消费，是否需要传递下去。false-会执行原有点击逻辑，true-只执行本次设置的点击逻辑
                    }
                })

                .update()
        }

        // 自定义UI
        btn_custom_ui.setOnClickListener {
            UpdateAppUtils
                .getInstance()
                .apkUrl(apkUrl)
                .updateTitle(updateTitle)
                .updateContent(updateContent)
                .updateConfig(UpdateConfig(alwaysShowDownLoadDialog = true))
                .uiConfig(
                    UiConfig(
                        uiType = UiType.CUSTOM,
                        customLayoutId = R.layout.view_update_dialog_custom
                    )
                )
                .setOnInitUiListener(object : OnInitUiListener {
                    override fun onInitUpdateUi(
                        view: View?,
                        updateConfig: UpdateConfig,
                        uiConfig: UiConfig
                    ) {
                        view?.findViewById<TextView>(R.id.tv_update_title)?.text = "版本更新啦"
                        view?.findViewById<TextView>(R.id.tv_version_name)?.text = "V2.0.0"
                        // do more...
                    }
                })
                .update()
        }

        // java使用示例
        btn_java_sample.setOnClickListener {
            startActivity(Intent(this, JavaDemoActivity::class.java))
        }

        // md5校验
        btn_check_md5.setOnClickListener {
            startActivity(Intent(this, CheckMd5DemoActivity::class.java))
        }

        // 高级使用
        btn_higher_level_use.setOnClickListener {
            // ui配置
            val uiConfig = UiConfig().apply {
                uiType = UiType.PLENTIFUL
                cancelBtnText = "下次再说"
                updateLogoImgRes = R.drawable.ic_update
                updateBtnBgRes = R.drawable.bg_btn
                titleTextColor = Color.BLACK
                titleTextSize = 18f
                contentTextColor = Color.parseColor("#88e16531")
            }

            // 更新配置
            val updateConfig = UpdateConfig().apply {
                force = true
                isDebug = true
                isApk = false
                checkWifi = true
                isShowNotification = true
                notifyImgRes = R.drawable.ic_logo
                apkSavePath = apkSavePaths
                apkSaveName = "update.bin"
            }

            UpdateAppUtils
                .getInstance()
                .apkUrl(apkUrl)
                .updateTitle(updateTitle)
                .updateContent(updateContent)
                .updateConfig(updateConfig)
                .uiConfig(uiConfig)
                .setUpdateDownloadListener(object : UpdateDownloadListener {
                    override fun onStart() {
                    }

                    override fun onDownload(progress: Int) {
                    }

                    override fun onFinish(filePath: String) {}

                    override fun onError(e: Throwable) {
                    }
                })
                .update()
        }

        // 正常安装
        btn_install.setOnClickListener {
            // 测试流程---(1、22升级23debug-debug  2、无app时升级debug)
            UpdateAppUtils
                .getInstance()
                .apkUrl(debugUrl_2731)
                .updateTitle("发现新版本")
                .updateConfig(
                    UpdateConfig(
                        isSilent = true,
                        alwaysShowDownLoadDialog = true,
                        installType = installType,
                        newVersionCode = newVersionCode_2731,
                        newApkType = newApkType,
                        packageName = Constant.SHOP_PACKAGE
                    )
                )
                .uiConfig(UiConfig(uiType = UiType.SIMPLE))
                .updateContent(newVersion_2731)
                .update()
        }

        // 卸载安装
        btn_uninstall.setOnClickListener {
            // 测试流程---23安装22(debug-debug)
            UpdateAppUtils
                .getInstance()
                .apkUrl(debugUrl_2722)
                .updateTitle("发现新版本")
                .updateConfig(
                    UpdateConfig(
                        isSilent = true,
                        alwaysShowDownLoadDialog = true,
                        installType = installType,
                        newVersionCode = newVersionCode_2722,
                        newApkType = newApkType,
                        packageName = Constant.SHOP_PACKAGE
                    )
                )
                .uiConfig(UiConfig(uiType = UiType.SIMPLE))
                .updateContent(newVersion_2722)
                .update()
        }

        // 同版本切换release
        btn_switch_release.setOnClickListener {
            // 测试流程---22安装22(debug-release)
            UpdateAppUtils
                .getInstance()
                .apkUrl(releaseUrl_2722)
                .updateTitle("发现新版本")
                .updateConfig(
                    UpdateConfig(
                        isSilent = true,
                        alwaysShowDownLoadDialog = true,
                        installType = installType,
                        newVersionCode = newVersionCode_2722,
                        newApkType = 2,
                        packageName = Constant.SHOP_PACKAGE
                    )
                )
                .uiConfig(UiConfig(uiType = UiType.SIMPLE))
                .updateContent(newVersion_2722)
                .update()
        }
        // 同版本切换debug
        btn_switch_debug.setOnClickListener {
            // 测试流程---22安装22(release-debug)
            newApkType = 1
            UpdateAppUtils
                .getInstance()
                .apkUrl(debugUrl_2722)
                .updateTitle("发现新版本")
                .updateConfig(
                    UpdateConfig(
                        isSilent = true,
                        alwaysShowDownLoadDialog = true,
                        installType = installType,
                        newVersionCode = newVersionCode_2722,
                        newApkType = 1,
                        packageName = Constant.SHOP_PACKAGE
                    )
                )
                .uiConfig(UiConfig(uiType = UiType.SIMPLE))
                .updateContent(newVersion_2722)
                .update()
        }

        //安装
        btn_install_test.setOnClickListener {
            val intent = Intent("com.mobilepower.terminal.message")
            intent.putExtra("type", 3)
            intent.putExtra("path", "/sdcard/Android/Update.apk")
            log("path===/sdcard/Android/Update.apk")
            sendBroadcast(intent)
        }

        //卸载
        btn_uninstall_test.setOnClickListener {
            val intent = Intent("com.mobilepower.terminal.message")
            intent.putExtra("type", 11)
            intent.putExtra("path", Constant.SHOP_PACKAGE)
            log("path===${Constant.SHOP_PACKAGE}")
            sendBroadcast(intent)
        }
    }
}